import os
import threading
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from reportservice.helpers import ApiResponse
import json
from datetime import datetime
from .yida_config import YidaClient
import requests

from .proofread import ai_proofread
from .docx_utils import read_docx
from oss_service.views import bucket
import tempfile

yida_client = YidaClient()
admin_user_id = "301546025724261514"


@csrf_exempt
@require_http_methods(["POST"])
def text_ai_proofreading(request):
    datasource = json.loads(request.body.decode())
    # print('datasource--->',datasource)
    report_data = yida_client.get_form_data_by_search_field(
        "FORM-77AB896AA10F470995C97484D1640B72LO36",
        admin_user_id,
        datasource
    )
    # print('report_data--->', json.loads(report_data[0].form_data['attachmentField_lwemw50p'])[0])
    file_info = json.loads(report_data[0].form_data['attachmentField_lwemw50p'])[0]
    full_download_url = yida_client.get_full_download_url(
        user_id=admin_user_id, 
        download_url=file_info['downloadUrl']
    )
    # 创建线程处理耗时操作
    threading.Thread(target=handle_file_operations, args=(file_info, full_download_url, datasource)).start()
    return ApiResponse.success("文件更新任务已启动，稍后完成")


def handle_file_operations(file_info, full_download_url, datasource):
    response = requests.get(full_download_url.body.result)
    if response.status_code == 200:
        # 创建临时目录
        temp_dir = tempfile.mkdtemp()
        file_path_upload = os.path.join(temp_dir, file_info['name'])
        with open(file_path_upload, 'wb') as f:
            f.write(response.content)
        print('缓存文件', file_path_upload)

        contents, doc = read_docx(file_path_upload)
        for i, content in enumerate(contents):
            print(f"正在解析修改第{i+1}句. {content.text}")
            ai_proofread(content=content)

        temp_dir_update = tempfile.mkdtemp()
        date_now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        file_path_update = os.path.join(temp_dir_update, f'update_{date_now}.docx')
        doc.save(file_path_update)

        # 上传到OSS
        filekey_update = f"ai_cloud/update/update_{date_now}.docx"
        bucket.put_object_from_file(filekey_update, file_path_update)
        sign_url_update = bucket.sign_url('GET', filekey_update, 3600)
        print('sign_url_update', sign_url_update)

        # 更新表单数据
        yida_client.update_form_data_by_field(
            "FORM-77AB896AA10F470995C97484D1640B72LO36",
            admin_user_id,
            datasource,
            {
                "attachmentField_lwemw50q": [
                    {
                        "downloadUrl": sign_url_update,
                        "name": "update.docx",
                        "previewUrl": sign_url_update,
                        "url": sign_url_update,
                        "ext": "docx"
                    }
                ]
            }
        )
    else:
        print("下载失败")